package com.scbo.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import com.scbo.DTO.Buildorder;
import com.scbo.DTO.ItemBO;
import com.scbo.DTO.eventSound;
import com.scbo.DTO.trainerBO;
import com.scbo.DTO.typeBO;
import com.scbo.common.ConvertTime;
import com.scbo.database.ScboDAO;
import com.scbo.main.R;
import com.scbo.utility.CalculateTime;

import android.R.array;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TrainActivity extends Activity implements OnInitListener {

	LinearLayout list1;
	TextView tvTimerMinute;
	TextView tvTimerSecond;
	Button btnStart;
	Button btnPause;
	Button btnReset;
	private boolean isPaused = false;
	public int mCurTime = 0;
	// public static MediaPlayer mp;
	AssetFileDescriptor afd;
	// eventSound fakeSupply;
	// eventSound fakeSCV;
	// eventSound fakeBarrack;
	typeBO fakeTvsT;
	// trainerBO train01;
	// trainerBO train02;
	// trainerBO train03;
	// List<trainerBO> listTrain;
	int[] arrayIdTv;

	// test scbo
	private ScboDAO datasource;
	Buildorder buildOrder;
	private List<ItemBO> listItems = null;
	// test TTS
	public static int REQUEST_CHECK_TTS_DATA = 1;
	private TextToSpeech mTts;

	/**
	 * test TTS
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
//		if (requestCode == REQUEST_CHECK_TTS_DATA) {
//			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//				// success, create the TTS instance
//				mTts = new TextToSpeech(this, this);
//			} else {
//				// missing data, install it
//				Intent installIntent = new Intent();
//				installIntent
//						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
//				startActivity(installIntent);
//			}
//			if (mTts != null) {
//				mTts.setLanguage(Locale.US);
//				String myText1 = "Did you sleep well?";
//				String myText2 = "I hope so, because it's time to wake up.";
//				mTts.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
//				mTts.speak(myText2, TextToSpeech.QUEUE_ADD, null);
//			}
//		}
		if (requestCode == REQUEST_CHECK_TTS_DATA) {
			if (resultCode == RESULT_OK) {
				Uri audioUri = data.getData();
				// make use of this MediaStore uri
				// e.g. store it somewhere
			} else {
				// react meaningful to problems
			}

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_train);
		buildOrder = (Buildorder) getIntent().getSerializableExtra(
				"buildOrder");
		datasource = new ScboDAO(this);
		datasource.open();

		initInstance();
		mTts = new TextToSpeech(getApplicationContext(), this);

	}

	@Override
	protected void onPause() {
		datasource.close();
		if (mTts != null) {
			mTts.stop();
			mTts.shutdown();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		datasource.close();
		super.onResume();
	}

	private void initInstance() {
		Log.d("Train", "build id" + buildOrder.getId());
		listItems = datasource.getItemsByIdType(buildOrder.getId());
		// listItems = datasource.getAllitemBO();
		for (int i = 0; i < listItems.size(); i++) {
			Log.d("Train", "Item id" + listItems.get(i).getId() + " , idtype "
					+ listItems.get(i).getBuildOrder().getId());
		}
		// fakeSupply = new eventSound(1, "supply", "supply.mp3", null, null);
		// fakeSCV = new eventSound(2, "scv", "scv.mp3", null, null);
		// fakeBarrack = new eventSound(3, "barrack", "barrack.mp3", null,
		// null);
		// fakeTvsT = new typeBO(1, "TvP Innovation’s CC First", "abc", "cdf",
		// 1, 1, 1000 * 30);
		// train01 = new trainerBO(fakeTvsT.getID(), fakeSupply, 2,
		// "10 - supply depot");
		// train02 = new trainerBO(fakeTvsT.getID(), fakeSCV, 10,
		// "14 – Command Center");
		// train03 = new trainerBO(fakeTvsT.getID(), fakeBarrack, 14,
		// "15 – 1st Barracks");
		// listTrain = new ArrayList<trainerBO>();
		//
		// listTrain.add(train01);
		// listTrain.add(train02);
		// listTrain.add(train03);
		arrayIdTv = new int[listItems.size()];
		LayoutInflater inflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		tvTimerMinute = (TextView) findViewById(R.id.txtTimeMinute);
		tvTimerSecond = (TextView) findViewById(R.id.txtTimeSecond);

		btnPause = (Button) findViewById(R.id.btnPause);
		btnPause.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				isPaused = true;
				btnStart.setEnabled(true);

			}
		});
		btnStart = (Button) findViewById(R.id.btnStart);
		btnStart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				isPaused = false;
				startProgress();
				UpdateUITask taskUI = new UpdateUITask();
				taskUI.execute(listItems);
				btnStart.setEnabled(false);

			}
		});
		btnReset = (Button) findViewById(R.id.btnReset);
		btnReset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isPaused = true;
				btnStart.setEnabled(true);
				resetUI();

				// test TTS
//				Intent checkTtsIntent = new Intent();
//				checkTtsIntent
//						.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
//				startActivityForResult(checkTtsIntent, REQUEST_CHECK_TTS_DATA);
			}
		});

		list1 = (LinearLayout) findViewById(R.id.layoutTrainList);
		for (int i = 0; i < listItems.size(); i++) {
			final View itemOfList = inflater.inflate(R.layout.item_train, null);
			// get event
			// eventSound event = listTrain.get(i).getEvent();
			ItemBO item = listItems.get(i);

			// set id to item
			// KhanhVQ
//			itemOfList.setId(item.getId());
			itemOfList.setId(i);
			// get id to array to can find view by id.
			arrayIdTv[i] = itemOfList.getId();

			list1.addView(itemOfList);
			int second = (int) (item.getTime()/1000);
			String time = ConvertTime.toNumberString(ConvertTime
					.toMinute(second)) + ":" + ConvertTime.toNumberString(ConvertTime
							.toSecond(second));
			TextView text1 = (TextView) itemOfList;
			text1.setText(time + " - " + item.getText());
		}

	}

	private void resetUI() {
		mCurTime = 0;
		for (int i = 0; i < arrayIdTv.length; i++) {
			TextView tvItem = (TextView) findViewById(arrayIdTv[i]);
			tvItem.setTextColor(getResources().getColor(R.color.xanhlacay));
		}
		tvTimerMinute.setText("00");
		tvTimerSecond.setText("00");
	}

	public void startProgress() {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {

				while (!isPaused) {

					try {
						if (!isPaused) {
							Thread.sleep(1000);
							if (!isPaused) {
								mCurTime++;
								Log.d("KHANHVQ", "current time: " + mCurTime);

								tvTimerMinute.post(new Runnable() {

									@Override
									public void run() {
										tvTimerMinute.setText(ConvertTime
												.toNumberString(ConvertTime
														.toMinute(mCurTime)));
										tvTimerSecond.setText(ConvertTime
												.toNumberString(ConvertTime
														.toSecond(mCurTime)));
									}
								});
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		new Thread(runnable).start();
	}

	private class UpdateUITask extends AsyncTask<List<ItemBO>, Integer, Void>
			implements OnCompletionListener {
		// HashMap<Integer, eventSound> hasmapEvent = new HashMap<Integer,
		// eventSound>();

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// mp = new MediaPlayer();
			// mp.setOnCompletionListener(this);
			// mp.reset();
			// mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
		}

		@Override
		protected Void doInBackground(List<ItemBO>... params) {
			List<ItemBO> listTraingBO = params[0];

			while (!isPaused) {
				for (int i = 0; i < listTraingBO.size(); i++) {
					if ((listTraingBO.get(i).getTime() / 1000) == mCurTime) {
						// eventSound eventSound =
						// listTraingBO.get(i).getEvent();
						// hasmapEvent.put(arrayIdTv[i], eventSound);
						publishProgress(arrayIdTv[i]);
						// try {
						// afd = getAssets().openFd(eventSound.getSound1());
						// if (afd != null) {
						// Log.d("KHANHVQ", eventSound.getSound1());
						// }
						// } catch (IOException e1) {
						// e1.printStackTrace();
						// }
						//
						// if (mp.isPlaying()) {
						// if (mp != null) {
						// mp.seekTo(0);
						// mp.stop();
						// }
						// }
						// try {
						// mp.reset();
						// mp.setDataSource(afd.getFileDescriptor(),
						// afd.getStartOffset(), afd.getLength());
						// mp.prepare();
						// mp.start();
						// // Thread.sleep(mp.getDuration());
						//
						// // if (mp != null && mp.isPlaying()) {
						// // Log.d("TAG------->", "player is running");
						// // mp.stop();
						// // Log.d("Tag------->", "player is stopped");
						// // mp.release();
						// // Log.d("TAG------->", "player is released");
						// //
						// // }
						// } catch (IllegalArgumentException e1) {
						// Log.d("KhanhVQ1", "1");
						// e1.printStackTrace();
						// } catch (IllegalStateException e1) {
						// Log.d("KhanhVQ1", "1a");
						// e1.printStackTrace();
						// } catch (IOException e1) {
						// e1.printStackTrace();
						// }

					}
				}
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			int id = values[0];
			int checkid = -1;
			if (!mTts.isSpeaking()) {
				if (checkid != id) {
					checkid = id;
					String speakText;
					if (!listItems.get(id).getTextToSpeech().trim().equals("")) {
						speakText  = listItems.get(id).getTextToSpeech().trim();
					} else {
						speakText  = listItems.get(id).getText().trim();
					}
					mTts.speak(speakText, TextToSpeech.QUEUE_FLUSH, null);
				}
				
			}
			
			TextView tvItem = (TextView) findViewById(id);
			tvItem.setTextColor(Color.BLUE);

		}

		@Override
		public void onCompletion(MediaPlayer mp) {
			// TODO Auto-generated method stub

		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// if (mp != null) {
		// if (mp.isPlaying()) {
		// mp.stop();
		// }
		// mp.release();
		// }
	}

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub
		if (status != TextToSpeech.ERROR) {
			mTts.setLanguage(Locale.US);
//			String toSpeak = write.getText().toString();
//			Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT)
//					.show();
//			ttobj.speak(" build more scv", TextToSpeech.QUEUE_ADD, null);
//			ttobj.speak(" pull out marine", TextToSpeech.QUEUE_ADD, null);
		}
	}
}
